/**
 * Created by freethy on 2017/10/27.
 */





define(['jquery',"core", "base64","hmac","sha1","hmacsha1"],function ($,CryptoJS){

    var up = function (option){

        //固定规则
        option.policyText = {"expiration": "2099-01-01T12:00:00.000Z","conditions": [["content-length-range", 0, 1048576000]]};

        //计算签名
        var wordArray = CryptoJS.enc.Utf8.parse(JSON.stringify(option.policyText));
        var policyBase64 = CryptoJS.enc.Base64.stringify(wordArray);
        var bytes = CryptoJS.HmacSHA1(policyBase64, option.accesskey);
        var signature = CryptoJS.enc.Base64.stringify(bytes);

        //构造表单
        var form = new FormData();
        form.append("key", option.key);
        form.append("signature", signature);
        form.append("policy", policyBase64);
        form.append("OSSAccessKeyId", option.accessid);
        form.append("success_action_status", "200");
        form.append("signature", signature);
        form.append("file", option.file);

        //创建上传对象
        var xhr = new XMLHttpRequest();
        xhr.open("post", option.host, true);

        //注册完成事件
        if(typeof (option.complete) != "undefined") {
            xhr.onloadend = function (e) {
                option.complete(e,option);
            }
        };

        //注册成功事件
        if(typeof (option.success) != "undefined") {
            xhr.onload = function (e) {
                option.success(e,option);
            }
        };

        //注册错误事件
        if(typeof (option.error) != "undefined") {
            xhr.onerror = function(e){
                option.error(e,option);
            }
        };

        //注册进度改变事件
        if(typeof (option.progress) != "undefined") {
            xhr.upload.onprogress = function(e){
                e.percent = (100 * (e.loaded / e.total)).toFixed(2);
                option.progress(e,option);
            }
        };

        //发送数据
        xhr.send(form);
    };

    //返回amd
    return {
        up: up
    };
});
